import json
from pyecharts.charts import Line
from pyecharts.options import TitleOpts, LabelOpts


def draw_line_chart(*file_name):
    """
    将传入的多份疫情确诊数据绘制成折线图
    :param file_name: 传入的多份疫情确诊数据
    :return: None
    """
    once = True  # x数据最后添加一份就行
    # 构建折线图对象
    line = Line()

    for name in file_name:
        # 数据处理
        f = open(name, 'r', encoding="UTF-8")
        data = f.read()
        to_del = "jsonp_1629344292311_69436("
        start = len(to_del)
        data = data[start:-2]

        # json转字典
        dic = json.loads(data)
        # print(type(dic), dic)

        # 取得国家名称
        country_name = dic['data'][0]['name']
        msg = country_name + '确诊人数'

        # 取得 'trend' key
        trend = dic['data'][0]['trend']
        # print(trend)

        if once:
            # 取日期数据用于x轴
            x_data = trend['updateDate'][:314]  # 取2020年数据
            line.add_xaxis(x_data)  # x数据添加一份就行
            once = False

        # 取统计数据用于y轴
        y_data = trend['list'][0]['data'][:314]
        line.add_yaxis(msg, y_data, label_opts=LabelOpts(is_show=False))  # 取消每个点都显示数据
        f.close()

    # 设置全局选项
    line.set_global_opts(
        # 标题设置
        title_opts=TitleOpts(title="2020年美日印三国确诊人数对比折线图", pos_left="center", pos_bottom="1%")
    )

    # 生成折线图
    line.render()


us_address = "D:/Code/KnowCode/my_python/可视化案例数据/折线图数据/美国.txt"
jp_address = "D:/Code/KnowCode/my_python/可视化案例数据/折线图数据/日本.txt"
id_address = "D:/Code/KnowCode/my_python/可视化案例数据/折线图数据/印度.txt"
draw_line_chart(us_address, jp_address, id_address)
